package com.fingard.dsp.bank.directbank.lzccb01;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.bankInterface.ITransaction;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7515TodayTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7516HisTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.RetAtsTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.detail.RetAtsTransDetail;
import com.fingard.io.FileHelper;
import com.fingard.text.MFSHelper;
import com.fingard.text.StringHelper;
import com.fingard.util.DateHelper;
import com.fingard.util.SmbFileUtil;
import com.fingard.xml.XElement;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

import static com.fingard.text.StringHelper.trimEndFileSp;

/**
 * @author Alon on 2019-10-12.
 * @version 1.0
 */
public class LZCCB01Transaction extends LZCCB01Base implements ITransaction {
    @Override
    public RetAtsTrans d_7516_HisTrans(Req7516HisTrans p_req7516) throws Exception {
        //历史明细查询返回ATS的对象
        RetAtsTrans retAts = new RetAtsTrans(p_req7516.reqHeader);
        retAts.writeStart();//写返回ATS的统一头部信息
        String tmpRespCode = "";
        String tmpRespInfo = "";

        try {
            Calendar tmpCalendarFrom = Calendar.getInstance();
            tmpCalendarFrom.setTime(p_req7516.getDateFrom());

            Calendar tmpCalendarTo = Calendar.getInstance();
            tmpCalendarTo.setTime(p_req7516.getDateTo());

            //按自然月循环查询
            int tmpIntDateFrom = 0;
            int tmpIntDateTo = 0;
            while (tmpIntDateFrom <= tmpIntDateTo && tmpRespCode.length() == 0) {
                Calendar tmpClndrStepTo = Calendar.getInstance();
                tmpClndrStepTo.setTime(tmpCalendarFrom.getTime());
                //判断是否跨月
                if (DateHelper.compareMonth(tmpCalendarFrom, tmpCalendarTo) == -1) {
                    //跨月则设置为月末
                    tmpClndrStepTo.set(Calendar.DAY_OF_MONTH, tmpClndrStepTo.getActualMaximum(Calendar.DAY_OF_MONTH));
                } else {
                    tmpClndrStepTo.setTime(tmpCalendarTo.getTime());
                }
                //赋值通用参数
                LZCCB01Header bankHeader = new LZCCB01Header();
                bankHeader.trCode = "200110";
                bankHeader.reqNo = p_req7516.reqHeader.reqSeqID;
                bankHeader.fileFlag = "1";//文件标识 0-报文 1-文件

                XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
                //写入LZCCB01通用的头部节点
                writeCommonHeader(xmlWriter, bankHeader);

                XElement tmpXElement = new XElement("body", "");
                tmpXElement.addChild(new XElement("acno", p_req7516.actNum));
                tmpXElement.addChild(new XElement("cur_code", convertCurToBank(p_req7516.actCur)));
                tmpXElement.addChild(new XElement("start_date", Format.Date8Format.format(tmpCalendarFrom.getTime())));//查询起始日期
                tmpXElement.addChild(new XElement("end_date", Format.Date8Format.format(tmpClndrStepTo.getTime())));//查询结束日期
                xmlWriter.writeXElement(tmpXElement);
                xmlWriter.writeEndDocument();

                String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());

                XmlTextReader tmpBkReader;
                if (tmpStrRet[0].length() == 0) {
                    StringBuilder tmpSbMsg = new StringBuilder();
                    tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                    if (tmpBkReader != null) {
                        String tmpRetCode = tmpBkReader.getFirstText("/ap/head/ret_code");
                        String tmpRetInfo = tmpBkReader.getFirstText("/ap/head/ret_info");
                        if (tmpRetCode != null && "0000".equals(tmpRetCode)) {
                            int tmpRecordNum = Integer.parseInt(tmpBkReader.getFirstText("/ap/body/record_num"));
                            int tmpFieldNum = Integer.parseInt(tmpBkReader.getFirstText("/ap/body/field_num"));
                            if (tmpRecordNum > 0) {
                                String tmpDataMFS = null;
                                String tmpFileFlag = tmpBkReader.getFirstText("/ap/head/file_flag");
                                if (tmpFileFlag != null && tmpFileFlag.equals("1")) {
                                    String tmpBatchFileName = tmpBkReader.getFirstText("/ap/body/file_name");
                                    //下载共享目录批量查询文件
                                    String downloadFilePath = trimEndFileSp(bankFront.bkTransFolder) + File.separator;//共享目录路径
                                    String p_FileFullPath = getTempFileDirectory() + File.separator + Format.Time6Format.format(new Date());//下载到的本地路径
                                    StringBuilder p_sb = new StringBuilder();
                                    if (SmbFileUtil.smbDownload(p_FileFullPath, downloadFilePath, tmpBatchFileName, p_sb) == 1) {
                                        WriteBankLogLn("共享目录文件，位于：" + downloadFilePath);
                                        WriteBankLogLn("文件下载成功，位于：" + p_FileFullPath);
                                        p_FileFullPath = p_FileFullPath + File.separator + tmpBatchFileName;
                                        tmpDataMFS = FileHelper.readFileText(p_FileFullPath, getCharset());
                                    } else {
                                        retAts.writeRespCode("-1");
                                        retAts.writeRespInfo(p_sb.toString());
                                        retAts.writeEnd();
                                        return retAts;
                                    }

                                    if (tmpDataMFS == null) {
                                        this.WriteBankLogLn("读取前置数据文件返回为null，需确认前置文件夹配置和文件是否存在");
                                    } else {
                                        this.WriteBankLogStep3(tmpDataMFS);
                                    }
                                } else {
                                    tmpDataMFS = tmpBkReader.getFirstText("/ap/body/serial_recode");
                                }
                                if (tmpDataMFS != null) {
                                    StringBuilder tmpSbLog = new StringBuilder();
                                    ArrayList<String[]> tmpArrayList = MFSHelper.getTextArray(tmpDataMFS, "|", tmpFieldNum, tmpRecordNum + 1, tmpSbLog);
                                    if (tmpSbLog.length() == 0) {
                                         /*0平台流水号|1账号|2货币码|3交易日期|4交易时间交易日期|5主机流水号|6交易行号|7户名|8对方账号|9对方货币码|10对方账号户名|
//                                         11对方账号开户行|12对方行号|13交易类别|14钞汇标志|15他行标志|16同城异地标志|17手续费|18交易来源|19发生额标志|
//                                         20被冲销流水号|21原交易日期|22现转标志|23借贷标志|24交易金额|25余额|26上笔余额|27冻结金额|28凭证种类|29凭证批次号|
//                                         30凭证号码|31交易码|32柜员号|33传票号|34摘要|35附言|36交易时间戳|37备注字段一|38备注字段二|39交易机构名称|40借方金额|
//                                         41贷方金额|*/
                                        for (int i = 1; i < tmpArrayList.size(); i++) {
                                            String[] tmpEachArr = tmpArrayList.get(i);
                                            RetAtsTransDetail tmpRetDetail = new RetAtsTransDetail();
                                            tmpRetDetail.actArea = p_req7516.actArea;//银行地区区域码
                                            tmpRetDetail.actNum = p_req7516.actNum;//银行账号
                                            tmpRetDetail.recAccNum = tmpEachArr[8].trim();//对方账号
                                            tmpRetDetail.recAccName = tmpEachArr[10].trim();//对方户名
                                            String tmpRecBank = StringHelper.convertToDBC(tmpEachArr[11]).trim();
                                            tmpRetDetail.recAccBank = tmpRecBank;//对方开户银行
                                            //交易日期
                                            if (tmpEachArr[3].length() == 8) {
                                                tmpRetDetail.tranDate = tmpEachArr[3].substring(0, 4) + "-" + tmpEachArr[3].substring(4, 6) + "-" + tmpEachArr[3].substring(6, 8);
                                            }
                                            //交易时间
                                            if (tmpEachArr[4].length() >= 14) {
                                                tmpRetDetail.tranTime = tmpEachArr[4].substring(0, 4) + "-" + tmpEachArr[4].substring(4, 6) + "-" + tmpEachArr[4].substring(6, 8) + " " + tmpEachArr[4].substring(8, 10) + ":" + tmpEachArr[4].substring(10, 12) + ":" + tmpEachArr[4].substring(12, 14);
                                            } else {
                                                tmpRetDetail.tranTime = tmpRetDetail.tranDate + " " + tmpEachArr[4].substring(0, 2) + ":" + tmpEachArr[4].substring(2, 4) + ":" + tmpEachArr[4].substring(4, 6);
                                            }
                                            tmpRetDetail.valueDate = tmpRetDetail.tranDate;//起息日期
                                            tmpRetDetail.tranAmt = tmpEachArr[24];//交易金额
                                            tmpRetDetail.accBal = tmpEachArr[25];//账号余额
                                            tmpRetDetail.postTimestamp = tmpEachArr[36];//时间戳
                                            if ("C".equals(tmpEachArr[23])) {
                                                tmpRetDetail.cdFlag = "2";//借贷标志
                                            } else if ("D".equals(tmpEachArr[23])) {
                                                tmpRetDetail.cdFlag = "1";//借贷标志
                                            }
                                            tmpRetDetail.billType = tmpEachArr[28];//票据类型
                                            tmpRetDetail.billNum = tmpEachArr[30];//票据号码
                                            tmpRetDetail.usage = tmpEachArr[34];//用途(摘要)
//                                            tmpRetDetail.abstr = "";//对账码(交易码)
//                                            tmpRetDetail.payCode = "";//支付信息
                                            tmpRetDetail.comment = tmpEachArr[35];//备注(附言)
//                                            tmpRetDetail.askNumber = "";//支付流水号？？
                                            tmpRetDetail.reqBatchNO = tmpEachArr[29];//支付批号(29凭证批次号)
                                            tmpRetDetail.cur = this.convertCurToATS(tmpEachArr[2]);//币种
//                                            tmpRetDetail.seqId = "";//序号
//                                            tmpRetDetail.isCollection = "";//是否现金池
                                            tmpRetDetail.originator = tmpEachArr[0];//银行返回流水号
                                            nodeAnalysic(tmpEachArr, tmpRetDetail, getCharset());
                                            retAts.writeRetDetail(tmpRetDetail);
                                        }
                                    } else {
                                        tmpRespCode = "-1";
                                        tmpRespInfo = tmpSbLog.toString();
                                    }
                                } else {
                                    tmpRespCode = "-1";
                                    tmpRespInfo = "数据为空";
                                }
                            }
                        } else {
                            tmpRespCode = "-1";
                            tmpRespInfo = tmpRetInfo;
                            break;
                        }
                    } else {
                        tmpRespCode = "-1";
                        tmpRespInfo = tmpSbMsg.toString();
                        break;
                    }
                } else {
                    tmpRespCode = "-1";
                    tmpRespInfo = tmpStrRet[1];
                    break;
                }


                tmpCalendarFrom = tmpClndrStepTo;
                tmpCalendarFrom.add(Calendar.DAY_OF_MONTH, 1);//下个月
                tmpIntDateFrom = Integer.parseInt(Format.Date8Format.format(tmpCalendarFrom.getTime()));
                tmpIntDateTo = Integer.parseInt(Format.Date8Format.format(tmpCalendarTo.getTime()));
            }
        } catch (Exception e) {
            retAts.writeRespCode("-1");
            retAts.writeRespInfo(e.getMessage());
            e.printStackTrace();
            retAts.writeEnd();
            return retAts;
        }


        if ("-1".equals(tmpRespCode)) {
            retAts.writeRespCode(tmpRespCode);
            retAts.writeRespInfo(tmpRespInfo);
        } else if (retAts.getWrittenRdCount() == 0) {
            retAts.writeRespCode("0");
            retAts.writeRespInfo("交易为空!");
        }

        retAts.writeEnd();

        return retAts;
    }

    @Override
    //当日明细查询调用历史明细查询方法
    public RetAtsTrans d_7515_TodayTrans(Req7515TodayTrans p_req7515) throws Exception {
        //通用b2e0035
        Req7516HisTrans tmpReq7516 = new Req7516HisTrans(p_req7515.reqHeader);
        tmpReq7516.actArea = p_req7515.actArea;
        tmpReq7516.actCur = p_req7515.actCur;
        tmpReq7516.actNum = p_req7515.actNum;
        tmpReq7516.higherLevelAct = p_req7515.higherLevelAct;
        String tmpStrToday = Format.Date8Format.format(new Date());
        tmpReq7516.dateFrom = tmpStrToday;
        tmpReq7516.dateTo = tmpStrToday;
        return d_7516_HisTrans(tmpReq7516);
    }
}
